 package com.suozq.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * @author 锁战强
 * @date 2022/04/07
 */
public class NoBlockServer {
    public static void main(String[] args) {
        try(ServerSocketChannel server = ServerSocketChannel.open();){
            server.bind(new InetSocketAddress(6666));
            server.configureBlocking(false);
            Selector selector = Selector.open();
            server.register(selector, SelectionKey.OP_ACCEPT);
            while(selector.select()>=0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                for(SelectionKey key : keys) {
                    if(key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        new Thread(new BlockServer.Dispatch(socketChannel)).start();
                    }else if (key.isAcceptable()) {
                        SocketChannel client = server.accept();
                        if(client!=null) {
                            client.configureBlocking(false);
                            client.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }
}
